package com.xinzhiduming.database;

import com.xinzhiduming.utils.AppConstant;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseOperator {

	public static String getCityNameFromDataBase(Context context) {
		String res = "";
		DatabaseHelper databaseHelper = new DatabaseHelper(context, AppConstant.TABLE_NAME);
		SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
		Cursor cursor = sqLiteDatabase.query(AppConstant.TABLE_NAME, new String[] { AppConstant.CITY_COLUMN_NAME_IN_DATABASE }, null, null, null, null, null);
		while (cursor.moveToNext()) {
			res = cursor.getString(cursor.getColumnIndex(AppConstant.CITY_COLUMN_NAME_IN_DATABASE));
		}
		cursor.close();
		sqLiteDatabase.close();
		return res;
	}
	
	public static String getCityCodeFromDataBase(Context context) {
		String res = "";
		DatabaseHelper databaseHelper = new DatabaseHelper(context, AppConstant.TABLE_NAME);
		SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
		Cursor cursor = sqLiteDatabase.query(AppConstant.TABLE_NAME, new String[] { "CITY_CODE" }, null, null, null, null, null);
		while (cursor.moveToNext()) {
			res = cursor.getString(cursor.getColumnIndex("CITY_CODE"));
		}
		cursor.close();
		sqLiteDatabase.close();
		return res;
	}
	
	public static void insertData(String data, Context context){
		ContentValues values = new ContentValues();
		DatabaseHelper databaseHelper = new DatabaseHelper(context, AppConstant.TABLE_NAME);
		SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
		values.clear();
		values.put(AppConstant.CITY_COLUMN_NAME_IN_DATABASE, data);
		if (sqLiteDatabase.update(AppConstant.TABLE_NAME, values, null, null) == 0) {
			sqLiteDatabase.insert(AppConstant.TABLE_NAME, null, values);
		}
		sqLiteDatabase.close();
	}
	
	public static void insertCityCode(String data, Context context){
		ContentValues values = new ContentValues();
		DatabaseHelper databaseHelper = new DatabaseHelper(context, AppConstant.TABLE_NAME);
		SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
		values.clear();
		values.put("CITY_CODE", data);
		if (sqLiteDatabase.update(AppConstant.TABLE_NAME, values, null, null) == 0) {
			sqLiteDatabase.insert(AppConstant.TABLE_NAME, null, values);
		}
		sqLiteDatabase.close();
	}
}
